<?php if (!defined("BASEPATH")) exit("No direct script access allowed"); ?>

<script type="text/javascript">
	Ext.onReady(function() {

		var winSubject; // edit ablak
		var subjectForm; // form panel

		var reader = new Ext.data.ArrayReader({}, [
			{name: 'subId'},
			{name: 'subSubId'},
			{name: 'subSubName'},
			{name: 'subName'}
		]);

		var store = new Ext.data.GroupingStore({
			reader: reader,
			data: [
				<?
					$first = TRUE;
					foreach($getSubject as $parentSubId => $subject) {
						if(isset($subject["children"])) {
							foreach($subject["children"] as $subId => $d) {
								echo	((!$first)?(","):(""))."[\"".$d["subId"]."\", \"".$d["subSubId"]."\", \"".$this->db->escape_str($d["subSubName"])."\", \"".$this->db->escape_str($d["subName"])."\"]";
								$first = FALSE;
							}
						}
					}
				?>
			],
			sortInfo:{field: 'subName', direction: "ASC"},
			groupField:'subSubName'
		});

		var grid = new Ext.grid.GridPanel({
			store: store,
			id: 'gridSubject',
			viewConfig:{
				emptyText: '<?=$this->db->escape_str($this->lang->line("THERE_IS_CURRENTLY_NO_DATA_TO_DISPLAY"))?>'
			},

			view: new Ext.grid.GroupingView({
				forceFit:true,
				startCollapsed: true,
				groupTextTpl: '{text} ({[values.rs.length]} {["<?=$this->db->escape_str($this->lang->line("ITEM"))?>"]})'
			}),

			columns: [
				{id: 'subSubName', header: '<?=$this->db->escape_str($this->lang->line("PARENT_SUBJECT"))?>', hidden: true, width: 150, sortable: true, dataIndex: 'subSubName'},
				{id: 'subName', header: '<?=$this->db->escape_str($this->lang->line("NAME"))?>', width: 400, sortable: true, dataIndex: 'subName'}
			],
			stripeRows: true,
			autoExpandColumn: 'subName',
			autoHeight: true,
			autoWidth: true,
			sm: new Ext.grid.RowSelectionModel({singleSelect:true}),
			listeners: {

				rowdblclick: function(grid, rowIndex, event) {
					if(rowIndex != 'new') {
						if(rowIndex == 'parent') {
							var record = event;
						} else {
							var record = grid.getStore().getAt(rowIndex);
						}
					} else {
						var record = new Object();
						record.data = new Object();
					}

					if(winSubject) {
						winSubject.close();
					}
					winSubject = new Ext.Window({
						iconCls: (rowIndex == 'new')?('application_form_add'):('application_form_edit'),
						layout:'fit',
						modal: true,
						width:500,
						floating: true,
						minWidth: 500,
						height:150,
						minHeight: 150,
						closeAction:'close',
						maximizable:true,
						title: (rowIndex == 'new')?('<?=$this->db->escape_str($this->lang->line("ADD_NEW_SUBJECT"))?>'):('<?=$this->db->escape_str($this->lang->line("EDITING_SUBJECT"))?> - ' + record.data.subName),

						listeners: {
							close: function() {
								Ext.get('center').load({url: '<?=site_url()?>admin/basic_data', scripts:true});
							}
						},

						items:[{

									border: false,

									items: subjectForm = new Ext.FormPanel({
										id: 'subjectForm',
										padding: 10,
										labelAlign: 'right',
										labelWidth: 110,
										autoHeight: true,
										autoWidth: true,
										border: false,
										defaultType: 'textfield',
										waitMsgTarget: true,
										items: [{
													hidden: true,
													inputType: 'hidden',
													name: 'sub_id',
													value: record.data.subId
											}, {
													fieldLabel: '<?=$this->db->escape_str($this->lang->line("NAME"))?>',
													name: 'sub_name',
													value: record.data.subName,
													maxLength: 255,
													maxLengthText: '<?=$this->db->escape_str($this->lang->line("YOU_HAVE_EXCEEDED_THE_MAXIMUM_LENGTH"))?>',
													allowBlank: false,
													blankText: '<?=$this->db->escape_str($this->lang->line("THIS_FIELD_IS_REQUIRED"))?>',
													anchor:'100%'
											}, new Ext.form.ComboBox({
													fieldLabel: '<?=$this->db->escape_str($this->lang->line("PARENT_SUBJECT"))?>',
													hiddenName:'sub_sub_id',
													store: new Ext.data.ArrayStore({
														fields: ['sub_id', 'sub_name'],
														url: '<?=site_url()?>admin/getSubject/',
														autoLoad: true
													}),
													valueField:'sub_id',
													displayField:'sub_name',
													editable: true,
													forceSelection: true,
													typeAhead: true,
													mode: 'local',
													triggerAction: 'all',
													emptyText:'...',
													selectOnFocus:true,
													allowBlank: true,
													hiddenValue: record.data.subSubId,
													value: record.data.subSubName,
													anchor:'100%'
											})
										]

									})

								}

							],

							bbar: {
								items: [{
									text: '<?=$this->db->escape_str($this->lang->line("SAVE"))?>',
									handler: save,
									icon: '<?=MEDIA?>icon/disk.png'
								}, {
									xtype: 'tbseparator'
								},{
									text: '<?=$this->db->escape_str($this->lang->line("CANCEL"))?>',
									handler: close,
									icon: '<?=MEDIA?>icon/cancel.png'
								}, {
									xtype: 'tbseparator'
								},{
									text: '<?=$this->db->escape_str($this->lang->line("RESET"))?>',
									handler: function() {
										subjectForm.getForm().reset();
									}
								}],
								buttonAlign : 'right'
							}

					});
					winSubject.show(this);

				}

			},

			border: false,
			frame:false,

			tbar: {
				items: [{
						icon: '<?=MEDIA?>icon/application_form_add.png',
						text: '<?=$this->db->escape_str($this->lang->line("ADD_NEW_SUBJECT"))?>',
						handler: function(){
							grid.fireEvent('rowdblclick', grid, 'new', new Object());
						}
					}, {
							xtype: 'tbseparator'
					}, {
						icon: '<?=MEDIA?>icon/application_form_delete.png',
						text: '<?=$this->db->escape_str($this->lang->line("DELETE_SUBJECT"))?>',
						ref: '../removeBtn',
						disabled: true,
						handler: function(){
							Ext.MessageBox.confirm('<?=$this->db->escape_str($this->lang->line("CONFIRMATION"))?>', '<?=$this->db->escape_str($this->lang->line("ARE_YOU_SURE_YOU_WOULD_LIKE_TO_DELETE_THE_SUBJECT_BELOW"))?> (' + Ext.getCmp('gridSubject').getSelectionModel().getSelections()[0].data.subName + ')?' , function(btn) {
								if(btn == 'yes') {
									Ext.Ajax.request({url: '<?=site_url()?>admin/basic_data_insert_update', params: 'del=1&subId=' + Ext.getCmp('gridSubject').getSelectionModel().getSelections()[0].data.subId, success: function() {
										Ext.get('center').load({url: '<?=site_url()?>admin/basic_data', scripts:true});
										}
									});
								}
							});
						}
					}, {
						xtype: 'tbseparator'
					}, {
						text:'<?=$this->db->escape_str($this->lang->line("CLEAR_ADD_GROUPING"))?>',
						icon: '<?=MEDIA?>icon/clear_grouping.png',
						handler : function() {
							if(Ext.getCmp('gridSubject').getColumnModel().getColumnById('subSubName').hidden) {
								Ext.getCmp('gridSubject').getColumnModel().getColumnById('subSubName').hidden = false;
								store.clearGrouping();
							} else {
								Ext.getCmp('gridSubject').getColumnModel().getColumnById('subSubName').hidden = true;
								store.groupBy('subSubName');
							}
						}
					}
				]
			}

		});

		grid.render('grid-table-subject');

		grid.getSelectionModel().on('selectionchange', function(sm){
			grid.removeBtn.setDisabled(sm.getCount() < 1);
		});

		function save() {
			if(!subjectForm.getForm().isValid()) {
				Ext.Msg.show({
					title:'<?=$this->db->escape_str($this->lang->line("ERROR"))?>',
					msg: '<?=$this->db->escape_str($this->lang->line("PLEASE_CORRECT_THE_ERRORS"))?>',
					buttons: Ext.Msg.OK,
					icon: Ext.MessageBox.WARNING
				});
			} else {
				if(subjectForm.getForm().isDirty()) {
					subjectForm.getForm().submit({
						url: '<?=site_url()?>admin/basic_data_insert_update',
						success: function(form, resp){
							if(resp.result.error) {
								Ext.Msg.show({
									title:'<?=$this->db->escape_str($this->lang->line("ERROR"))?>',
									msg: resp.result.error,
									buttons: Ext.Msg.OK,
									icon: Ext.MessageBox.ERROR
								});
							} else {
								winSubject.close();
							}
						}
					});
				} else {
					winSubject.close();
				}
			}
		};

		function close() {
			winSubject.close();
		};

	})
</script>

<div id="grid-table-subject"></div>

<? exit; ?>

<script type="text/javascript">
	Ext.onReady(function() {

		var winSubject; // edit ablak
		var subjectForm; // form panel

		<? foreach($getSubject as $parentSubId => $subject) { ?>

		var store_<?=$parentSubId?> = new Ext.data.JsonStore({
			//sortInfo: {field: 'subName', direction: 'ASC'},
			//remoteSort: false,
			data: [
				<?
					if(isset($subject["children"])) {
						$ii = 0;
						foreach($subject["children"] as $subId => $d) {
							echo	(($ii)?(","):(""))."{\"subId\": \"".$d["subId"]."\", \"subSubId\": \"".$d["subSubId"]."\", \"subSubName\": \"".$d["subSubName"]."\", \"subName\": \"".$this->db->escape_str($d["subName"])."\"}";
							$ii++;
						}
					}
				?>
			],
			fields: [
				{name: 'subId'},
				{name: 'subSubId'},
				{name: 'subSubName'},
				{name: 'subName'}
			]
		});

		var grid_<?=$parentSubId?> = new Ext.grid.GridPanel({
			store: store_<?=$parentSubId?>,
			id: 'grid_<?=$parentSubId?>',
			title: '<?=$this->db->escape_str($this->lang->line("PARENT_SUBJECT"))?>: <?=$this->db->escape_str($this->db->escape_str($subject["subName"]))?>',
			viewConfig:{
				emptyText: '<?=$this->db->escape_str($this->lang->line("THERE_IS_CURRENTLY_NO_DATA_TO_DISPLAY"))?>'
			},
			columns: [
				{id: 'subName', header: '<?=$this->db->escape_str($this->lang->line("NAME"))?>', width: 300, sortable: false, dataIndex: 'subName'}
			],
			stripeRows: true,
			autoExpandColumn: 'subName',
			autoHeight: true,
			autoWidth: true,
			sm: new Ext.grid.RowSelectionModel({singleSelect:true}),
			listeners: {

				rowdblclick: function(grid, rowIndex, event) {
					if(rowIndex != 'new') {
						if(rowIndex == 'parent') {
							var record = event;
						} else {
							var record = grid.getStore().getAt(rowIndex);
						}
					} else {
						var record = new Object();
						record.data = new Object();
					}

					if(winSubject) {
						winSubject.close();
					}
					winSubject = new Ext.Window({
						iconCls: (rowIndex == 'new')?('application_form_add'):('application_form_edit'),
						layout:'fit',
						modal: true,
						width:500,
						floating: true,
						minWidth: 500,
						height:150,
						minHeight: 150,
						closeAction:'close',
						maximizable:true,
						title: (rowIndex == 'new')?('<?=$this->db->escape_str($this->lang->line("ADD_NEW_SUBJECT"))?>'):('<?=$this->db->escape_str($this->lang->line("EDITING_SUBJECT"))?> - ' + record.data.subName),

						listeners: {
							close: function() {
								Ext.get('center').load({url: '<?=site_url()?>admin/basic_data', scripts:true});
							}
						},

						items:[{

									border: false,

									items: subjectForm = new Ext.FormPanel({
										id: 'subjectForm',
										padding: 10,
										labelAlign: 'right',
										labelWidth: 110,
										autoHeight: true,
										autoWidth: true,
										border: false,
										defaultType: 'textfield',
										waitMsgTarget: true,
										items: [{
													hidden: true,
													inputType: 'hidden',
													name: 'sub_id',
													value: record.data.subId
											}, {
													fieldLabel: '<?=$this->db->escape_str($this->lang->line("NAME"))?>',
													name: 'sub_name',
													value: record.data.subName,
													maxLength: 255,
													maxLengthText: '<?=$this->db->escape_str($this->lang->line("YOU_HAVE_EXCEEDED_THE_MAXIMUM_LENGTH"))?>',
													allowBlank: false,
													blankText: '<?=$this->db->escape_str($this->lang->line("THIS_FIELD_IS_REQUIRED"))?>',
													anchor:'100%'
											}, new Ext.form.ComboBox({
													fieldLabel: '<?=$this->db->escape_str($this->lang->line("PARENT_SUBJECT"))?>',
													hiddenName:'sub_sub_id',
													store: new Ext.data.ArrayStore({
														fields: ['sub_id', 'sub_name'],
														url: '<?=site_url()?>admin/getSubject/',
														autoLoad: true
													}),
													valueField:'sub_id',
													displayField:'sub_name',
													editable: false,
													mode: 'local',
													triggerAction: 'all',
													emptyText:'...',
													selectOnFocus:true,
													allowBlank: true,
													hiddenValue: record.data.subSubId,
													value: record.data.subSubName,
													anchor:'100%'
											})
										]

									})

								}

							],

							bbar: {
								items: [{
									text: '<?=$this->db->escape_str($this->lang->line("SAVE"))?>',
									handler: save,
									icon: '<?=MEDIA?>icon/disk.png'
								}, {
									xtype: 'tbseparator'
								},{
									text: '<?=$this->db->escape_str($this->lang->line("CANCEL"))?>',
									handler: close,
									icon: '<?=MEDIA?>icon/cancel.png'
								}, {
									xtype: 'tbseparator'
								},{
									text: '<?=$this->db->escape_str($this->lang->line("CANCEL"))?>',
									handler: function() {
										subjectForm.getForm().reset();
									}
								}],
								buttonAlign : 'right'
							}

					});
					winSubject.show(this);

				}

			},

			border: false,
			frame:false,

			tbar: {
				items: [{
						icon: '<?=MEDIA?>icon/application_form_add.png',
						text: '<?=$this->db->escape_str($this->lang->line("EDITING_PARENT_SUBJECT"))?>',
						handler: function() {
							record = new Object();
							record.data = new Object();
							record.data.subId = '<?=$parentSubId?>';
							record.data.subName = '<?=$this->db->escape_str($subject["subName"])?>';
							grid_<?=$parentSubId?>.fireEvent('rowdblclick', grid_<?=$parentSubId?>, 'parent', record);
						}
					}, {
							xtype: 'tbseparator'
					}, {
						icon: '<?=MEDIA?>icon/application_form_delete.png',
						text: '<?=$this->db->escape_str($this->lang->line("DELETE_PARENT_SUBJECT"))?>',
						handler: function(){
							Ext.MessageBox.confirm('<?=$this->db->escape_str($this->lang->line("CONFIRMATION"))?>', '<?=$this->db->escape_str($this->lang->line("ARE_YOU_SURE_YOU_WOULD_LIKE_TO_DELETE_THE_SUBJECT_BELOW"))?> (<?=$this->db->escape_str($subject["subName"])?>)?' , function(btn) {
								if(btn == 'yes') {
									Ext.Ajax.request({url: '<?=site_url()?>admin/basic_data_insert_update', params: 'del=1&subId=<?=$parentSubId?>', success: function() {
										Ext.get('center').load({url: '<?=site_url()?>admin/basic_data', scripts:true});
										}
									});
								}
							});
						}
					}, {
							xtype: 'tbseparator'
					}, {
						icon: '<?=MEDIA?>icon/application_form_add.png',
						text: '<?=$this->db->escape_str($this->lang->line("ADD_NEW_SUBJECT"))?>',
						handler: function(){
							grid_<?=$parentSubId?>.fireEvent('rowdblclick', grid_<?=$parentSubId?>, 'new', new Object());
						}
					}, {
							xtype: 'tbseparator'
					}, {
						icon: '<?=MEDIA?>icon/application_form_delete.png',
						text: '<?=$this->db->escape_str($this->lang->line("DELETE_SUBJECT"))?>',
						ref: '../removeBtn',
						disabled: true,
						handler: function(){
							Ext.MessageBox.confirm('<?=$this->db->escape_str($this->lang->line("CONFIRMATION"))?>', '<?=$this->db->escape_str($this->lang->line("ARE_YOU_SURE_YOU_WOULD_LIKE_TO_DELETE_THE_SUBJECT_BELOW"))?> (' + Ext.getCmp('grid_<?=$parentSubId?>').getSelectionModel().getSelections()[0].data.subName + ')?' , function(btn) {
								if(btn == 'yes') {
									Ext.Ajax.request({url: '<?=site_url()?>admin/basic_data_insert_update', params: 'del=1&subId=' + Ext.getCmp('grid_<?=$parentSubId?>').getSelectionModel().getSelections()[0].data.subId, success: function() {
										Ext.get('center').load({url: '<?=site_url()?>admin/basic_data', scripts:true});
										}
									});
								}
							});
						}
					}
				]
			}

		});

		grid_<?=$parentSubId?>.render('grid-table-subject');

		grid_<?=$parentSubId?>.getSelectionModel().on('selectionchange', function(sm){
			grid_<?=$parentSubId?>.removeBtn.setDisabled(sm.getCount() < 1);
		});

		<? } ?>

		function save() {
			if(!subjectForm.getForm().isValid()) {
				Ext.Msg.show({
					title:'<?=$this->db->escape_str($this->lang->line("ERROR"))?>',
					msg: '<?=$this->db->escape_str($this->lang->line("PLEASE_CORRECT_THE_ERRORS"))?>',
					buttons: Ext.Msg.OK,
					icon: Ext.MessageBox.WARNING
				});
			} else {
				if(subjectForm.getForm().isDirty()) {
					subjectForm.getForm().submit({
						url: '<?=site_url()?>admin/basic_data_insert_update',
						success: function(form, resp){
							if(resp.result.error) {
								Ext.Msg.show({
									title:'<?=$this->db->escape_str($this->lang->line("ERROR"))?>',
									msg: resp.result.error,
									buttons: Ext.Msg.OK,
									icon: Ext.MessageBox.ERROR
								});
							} else {
								winSubject.close();
							}
						}
					});
				} else {
					winSubject.close();
				}
			}
		};

		function close() {
			winSubject.close();
		};

	})
</script>

<div id="grid-table-subject"></div>